package com.streamer.app.fragment

import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.streamer.app.R
import com.streamer.app.adapter.UserListAdapter
import com.streamer.app.bean.LiveBean
import com.streamer.app.bean.LoginBean
import com.streamer.app.databinding.FragmentUsersBinding
import com.streamer.app.model.User
import com.streamer.app.model.UserRole
import com.streamer.app.utils.BottomSheetUtils
import com.streamer.app.utils.ToastUtil
import com.streamer.app.utils.UserManager

class UsersFragment : BaseFragment<FragmentUsersBinding>() {


    private var liveDisableUserListLVFlag = false
    private var liveDefriendUserListLVFlag = false


    private var mLiveUserCount: LoginBean? = null

    private lateinit var tvDisableCount: TextView
    private lateinit var tvBackName: TextView
    private var mliveData: LiveBean? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mliveData = (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arguments?.getSerializable(ARG_LIVE_DATA, LiveBean::class.java)
        } else {
            @Suppress("DEPRECATION") arguments?.getSerializable(ARG_LIVE_DATA)
        }) as LiveBean?
        viewMode.getLiveInfo()

        // 订阅统计更新
        viewMode.LiveUserCountLV.observe(requireActivity()) {
            if (it != null) {
                mLiveUserCount = it

                if (::tvDisableCount.isInitialized) {
                    // 已经初始化，可以安全使用
                    tvDisableCount.text = "禁言名单(${mLiveUserCount?.disableCount.toString()})"
                }
                if (::tvBackName.isInitialized) {
                    tvBackName.text = "踢出房间名单(${mLiveUserCount?.defriendCount.toString()})"
                }
                showUserListDialog(_binding.root)

            }
        }

        // 监听禁言/踢出/黑名单等操作成功回调，刷新列表和统计
        viewMode.PublishCouponLV.observe(requireActivity()) {

            // 操作成功后，刷新用户统计与用户列表
            val liveId = mliveData?.id?.toString() ?: ""
            if (liveId.isNotEmpty()) {
                viewMode.liveUserCount(liveId)
                viewMode.pageQuery(liveId, pageSize, currentPage)
            }
        }
    }


    override fun initView() {
        setupUserListListeners(_binding.root)
    }

    override fun onResume() {
        super.onResume()
        viewMode.pageQuery(mliveData?.id ?: "", pageSize, currentPage)

    }

    private fun showUserListDialog(root: View) {

        viewMode.LiveInfoLV.observe(requireActivity()) {
            if (it != null) {
                mliveData = it
                Log.d("xxxx", "liveRoomNo=======${it?.liveRoomNo}")
                //获取直播间历史评论
                viewMode.messageHistory(it?.id.toString())

            }
        }
        tvDisableCount = root.findViewById<TextView>(R.id.tvDisableCount).apply {
            text = "禁言名单(${mLiveUserCount?.disableCount.toString()})"
        }
        tvBackName = root.findViewById<TextView>(R.id.tvBackName).apply {
            text = "踢出房间名单(${mLiveUserCount?.defriendCount.toString()})"
        }

    }

    private fun setupUserListListeners(view: View) {


        val recyclerView = view.findViewById<RecyclerView>(R.id.rv_user_list)
        recyclerView.layoutManager = LinearLayoutManager(requireContext())

        val adapter = UserListAdapter(
            users = mutableListOf(), onUserAction = { user, action ->
                when (action) {
                    "mute" -> {
                        Toast.makeText(requireContext(), "禁言 ${user.name}", Toast.LENGTH_SHORT)
                            .show()
                        viewMode.userDisable(user.id)
                    }

                    "unmute" -> {
                        viewMode.userDisable(user.id)
                        Toast.makeText(
                            requireContext(), "解除禁言 ${user.name}", Toast.LENGTH_SHORT
                        ).show()

                    }

                    "kick" -> {
                        viewMode.userDefriend(user.id)
                    }

                    "blacklist" -> {
                        viewMode.blacklist(user.id)
                        Toast.makeText(
                            requireContext(), "加入黑名单 ${user.name}", Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            }, isMutedList = false
        )
        recyclerView.adapter = adapter

        viewMode.LiveUserListLV.observe(viewLifecycleOwner) { liveUserList ->
            if (!liveUserList.isNullOrEmpty()) {
                val users = mutableListOf<User>()

                liveUserList.forEach { liveUser ->
                    val role = when (liveUser.userType) {
                        1 -> UserRole.ASSISTANT
                        2 -> UserRole.ASSISTANT
                        3 -> UserRole.VIEWER
                        4 -> UserRole.VIEWER
                        5 -> UserRole.STREAMER
                        else -> UserRole.VIEWER
                    }
                    users.add(
                        User(
                            id = liveUser.id,
                            name = liveUser.userNick,
                            avatar = liveUser.avatar,
                            role = role,
                            isMuted = liveUser.disable,
                            isKicked = liveUser.defriend,
                            isBlacklisted = liveUser.blacklist,
                            joinTime = liveUser.joinTime
                        )
                    )
                }
                adapter.updateUsers(users)
            } else {
                val defaultUsers = mutableListOf(
                    User(
                        UserManager.getLocalUser()?.id.toString(),
                        UserManager.getLocalUser()?.nickName.toString(),
                        UserManager.getLocalUser()?.avatar.toString(),
                        UserRole.STREAMER
                    )
                )
                adapter.updateUsers(defaultUsers)
            }

            // 底部操作栏
            _binding.btnMutedList.setOnClickListener {
                if (!liveDisableUserListLVFlag) {
                    // 调用API获取禁言用户列表
                    viewMode.pageQuery(
                        mliveData?.id.toString(),
                        pageSize,
                        currentPage,
                        disable = true
                    )
                }
                liveDisableUserListLVFlag = true

            }

            //踢出黑名单
            view.findViewById<View>(R.id.btn_kicked_list).setOnClickListener {
                if (!liveDefriendUserListLVFlag) {
                    viewMode.pageQuery(
                        mliveData?.id.toString(),
                        pageSize,
                        currentPage,
                        defriend = true
                    )
                }
                liveDefriendUserListLVFlag = true

                // 调用API获取踢出用户列表
            }

            // 观察禁言用户列表数据（移到外部，避免重复注册）
            viewMode.LiveDisableUserListLV.observe(requireActivity()) { disableUserList ->
                liveDisableUserListLVFlag = false
                if (disableUserList != null && disableUserList.isNotEmpty()) {
                    // 将API数据转换为User对象
                    val mutedUsers = disableUserList.map { liveUser ->
                        val userRole = when (liveUser.userType) {
                            1 -> UserRole.ASSISTANT  // 助教
                            2 -> UserRole.ASSISTANT  // 销售
                            3 -> UserRole.VIEWER     // 外部用户
                            4 -> UserRole.VIEWER     // 虚拟用户
                            5 -> UserRole.STREAMER   // 主播-+*
                            else -> UserRole.VIEWER
                        }
                        User(
                            id = liveUser.id,
                            name = liveUser.userNick,
                            avatar = liveUser.avatar,
                            role = userRole,
                            isMuted = liveUser.disable,
                            isKicked = liveUser.defriend,
                            isBlacklisted = liveUser.blacklist,
                            joinTime = liveUser.joinTime
                        )
                    }

                    // 显示禁言名单弹窗
                    BottomSheetUtils.showMutedListDialog(
                        context = requireActivity(),
                        mutedUsers = mutedUsers,
                        onUnmuteUser = { user ->
                            // 调用解除禁言API
                            viewMode.userDisable(user.id)

                            ToastUtil.toastShortMessage("解除禁言: ${user.name}")
                        },
                        onUnmuteAll = {
                            // 批量解除禁言
                            mutedUsers.forEach { user ->
                                viewMode.userDisable(user.id)
                            }
                            ToastUtil.toastShortMessage("全部解禁")
                        })
                } else {
                    // 如果没有禁言用户，显示空状态
                    ToastUtil.toastShortMessage("暂无禁言用户")
                }
            }

            // 观察踢出用户列表数据（移到外部，避免重复注册）
            viewMode.LiveDefriendUserListLV.observe(requireActivity()) { defriendUserList ->
                liveDefriendUserListLVFlag = false
                if (defriendUserList != null && defriendUserList.isNotEmpty()) {
                    // 将API数据转换为User对象
                    val kickedUsers = defriendUserList.map { liveUser ->
                        val userRole = when (liveUser.userType) {
                            1 -> UserRole.ASSISTANT  // 助教
                            2 -> UserRole.ASSISTANT  // 销售
                            3 -> UserRole.VIEWER     // 外部用户
                            4 -> UserRole.VIEWER     // 虚拟用户
                            5 -> UserRole.STREAMER   // 主播
                            else -> UserRole.VIEWER
                        }

                        User(
                            id = liveUser.id,
                            name = liveUser.userNick,
                            avatar = liveUser.avatar,
                            role = userRole,
                            isMuted = liveUser.disable,
                            isKicked = liveUser.defriend,
                            isBlacklisted = liveUser.blacklist,
                            joinTime = liveUser.joinTime
                        )
                    }

                    // 显示踢出名单弹窗
                    BottomSheetUtils.showKickedListDialog(
                        context = requireActivity(),
                        kickedUsers = kickedUsers,
                        onUnmuteUser = { user ->
                            // 调用恢复用户API
                            viewMode.userDefriend(user.id)
                            ToastUtil.toastShortMessage("恢复用户: ${user.name}")
                        },
                        onUnmuteAll = {
                            // 批量恢复用户
                            kickedUsers.forEach { user ->
                                viewMode.userDefriend(user.id)
                            }
                            ToastUtil.toastShortMessage("全部恢复")
                        })
                } else {
                    // 如果没有踢出用户，显示空状态
                    ToastUtil.toastShortMessage("暂无踢出用户")
                }
            }
        }



    }

    companion object {
        private const val ARG_LIVE_DATA = "liveData"

        private const val ARG_ROOM_ID = "roomId"
        fun newInstance(roomId: String, mliveData: LiveBean?): UsersFragment {
            val f = UsersFragment()
            val b = Bundle()
            b.putString(ARG_ROOM_ID, roomId)
            b.putSerializable(ARG_LIVE_DATA, mliveData)

            f.arguments = b
            return f
        }
    }
}